package com.impress;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.text.TextUtils;

import com.impress.Utility.HttpForbiddenException;
import com.impress.Utility.BadAccountException;
import com.impress.Utility.HttpUnauthorizedException;
import com.impress.service.GDataClient;

//import android.util.Log;

public class GoogleAccount {

	 
	public GoogleAccount() {
		super();
		// TODO Auto-generated constructor stub
	}
	public GoogleAccount(String _email, String _password, String _token,
			String _auth) {
		super();
		this._email = _email;
		this._password = _password;
		this._token = _token;
		this._auth = _auth;
	}
	
	public GoogleAccount(GoogleAccount account){
		super();
		_email = account._email;
		_password = account._password;
		_auth = account._auth;
		_token = account._token;
	}


	/**
	 * 用户的账号名称
	 */
	private String _email;
	/**
	 * 用户的密码
	 */
	private String _password;
	/**
	 * 用于请求API calls的Token字串(seems that this token expires very quickly.)
	 */
	private String _token;
	/**
	 * 用户验证身份成功后返回的Authentication Key.用作发起http请求的头.
	 */
	private String _auth;
	
	public String get_email() {
		return _email;
	}
	public void set_email(String _email) {
		this._email = _email;
	}
	public String get_password() {
		return _password;
	}
	public void set_password(String _password) {
		this._password = _password;
	}
	public String get_token() {
		return _token;
	}
	public void set_token(String _token) {
		this._token = _token;
	}
	public void set_auth(String _auth){
		this._auth = _auth;
	}
	public String get_auth(){
		return _auth;
	}
	
	/**
	 * 判断账户是否为空
	 * @return 若账户为空（用户名或密码为空）则返回true; 否则返回false.
	 */
	public boolean IsEmpty(){
		if (TextUtils.isEmpty(_email) || TextUtils.isEmpty(_password)) {
			return true;
		}
		return false;
	}
	
	/**
	 * 用户登录；设置Auth值。
	 * returns either an HTTP 200, or an HTTP 403.
	 * A failure response contains an error code.
	 * Error code may be used in this application for invalid email or password : 
	 * Error=BadAuthentication.
	 * @return 成功取得Auth值返回true，否则返回false.
	 * @throws Exception BadAccountException HttpForbiddenException SocketTimeoutException ConnectTimeoutException
	 */
	public Boolean Login() throws Exception{

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (IsEmpty()) {
			throw new BadAccountException("email or password is requested.");
		}
		params.add(new BasicNameValuePair("Email", this.get_email()));
		params.add(new BasicNameValuePair("Passwd", this.get_password()));
		params.add(new BasicNameValuePair("source", "MobileGR"));
		params.add(new BasicNameValuePair("service", "reader"));

		try{
		String responseString = GDataClient.makePost(Utility.GOOGLE_LOGIN_URL, params, null);
		int indexAuth = responseString.indexOf("Auth=")+5;
		if(indexAuth>5){
			set_auth(responseString.substring(indexAuth));
			if(get_auth()!=null && get_auth()!=""){
				//setGoogleToken();
				return true;
			}
		}
		}catch (Exception e) {
			if(e instanceof HttpForbiddenException){
				throw new BadAccountException("invalid account info.");
			}
			else{
				throw e;
			}
		}

		return false;
	}
	
	
//	public void setGoogleAuth(){
//
//		List<NameValuePair> params = new ArrayList<NameValuePair>();
//		params.add(new BasicNameValuePair("Email", this.get_email()));
//		params.add(new BasicNameValuePair("Passwd", this.get_password()));
//		params.add(new BasicNameValuePair("source", "MobileGR"));
//		params.add(new BasicNameValuePair("service", "reader"));
//		try {
//			String responseString = Utility.makePost(Utility.GOOGLE_LOGIN_URL, params, null);
//			int indexAuth = responseString.indexOf("Auth=")+5;
//			if(indexAuth>5){
//				set_auth(responseString.substring(indexAuth));
//			}
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
//	}
	
	/**
	 * 取得并设置Token字串
	 * ensure the auth is valid or throw a BadAccountException for checking account.
	 */
	public void setGoogleToken() throws Exception{
		try {
			
			if(get_auth()!=null && get_auth()!=""){
				String responseString = GDataClient.doGet(Utility.TOKEN_URL, null, get_auth());
				set_token(responseString);
			}
			else {
				if (Login()) {
					String responseString = GDataClient.doGet(Utility.TOKEN_URL, null, _auth);
					set_token(responseString);
				}
			}
		} catch (Exception e) {
			if (e instanceof HttpUnauthorizedException) { //handle expired auth.
				if (Login()) {
					String responseString = GDataClient.doGet(Utility.TOKEN_URL, null, _auth);
					set_token(responseString);
				}
			}else {
				throw e;
			}
		}
	}
	
}
